package com.xinghen.ace.auth.interceptor;

import com.xinghen.ace.auth.common.jwt.IJWTInfo;
import com.xinghen.ace.auth.configuration.UserConfiguration;
import com.xinghen.ace.auth.util.JwtTokenUtil;
import com.xinghen.ace.common.constant.CommonConstants;
import com.xinghen.ace.common.util.ThreadContextHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xinghen
 * @ClassName: UserAuthRestInterceptor
 * @Package: com.xinghen.ace.auth.interceptor
 * @Description 用户权限拦截器
 * @create 2018/5/4 15:48
 */
public class UserAuthRestInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserConfiguration userConfiguration;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(userConfiguration.getUserTokenHeader());
        IJWTInfo infoFromToken = jwtTokenUtil.getInfoFromToken(token);
        ThreadContextHelper.set(CommonConstants.CONTEXT_KEY_USER_NAME, infoFromToken.getUniqueName());
        ThreadContextHelper.set(CommonConstants.CONTEXT_KEY_NAME, infoFromToken.getName());
        ThreadContextHelper.set(CommonConstants.CONTEXT_KEY_USER_ID, infoFromToken.getId());
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadContextHelper.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
